package main {
	import flash.display.*;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.geom.ColorTransform;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	import inter.IChart;
	
	import model.Layer;
	import model.LayerAction;
	
	import mx.controls.Alert;
	import mx.controls.Image;
	import mx.core.UIComponent;
	import mx.events.DragEvent;
	import mx.events.EffectEvent;
	import mx.events.FlexEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	import spark.components.Application;
	import spark.effects.Fade;
	
	import util.*;
	
	/**
	 * 挂图展示主类
	 * @author liupj
	 */
	public class Chart extends Application implements IChart {
/*********************************************属性定义区（START）****************************************************************************/
		/*当前显示的图层*/
		private var currentLayer : Layer;
		
		/*当前显示的图片*/
		private var _currentImage : Image;
		
		/*当前页面*/
		private var currentPageId : String;
		
		/*当前页面预加载的图层数组*/
		private var preloadingLayerArray : Array = new Array();
		
		/*当前页面预加载的图片对象数组*/
		private var preloadingImageArray : Array  = new Array();
		
		/*当前页面底图图层*/
		private var _baseLayer : Layer;
		
		/*当前包含图片的容器，现在为panel*/
		private var _container : DisplayObjectContainer;
		
		/*当前页面底图图层的对应图片Loader*/
		private var _baseImage : Image;
		
		/*当前图层的最大排序号*/
		private var _currentSorting : Number;
/*********************************************属性定义区（END）****************************************************************************/

/*********************************************方法定义区（START）****************************************************************************/
		/*构建新图层*/
		public function buildNewImage(layer : Layer) : Image {
			if (layer.layerType != Const.LAYER_TYPE_STATIC_IMAGE) {
				return null;
			}
			
			var image : Image = new Image();
			image.id = layer.layerId;
			image.source = layer.picPath;
			
			//图层指定了大小和位置
			if (layer.fullArea == Const.FULL_SCREEN_NO) {
				image.x = layer.xPos;
				image.y = layer.yPos;
				image.width = layer.width;
				image.height = layer.height;
			} else {
				image.x = 0;
				image.y = 0;
				image.width = container.width;
				image.height = container.height;
			}
			
			image.alpha = layer.transparency;
			
			if (layer.color != -1) {
				var colorInfo:ColorTransform = image.transform.colorTransform;
				colorInfo.color = layer.color;
				image.transform.colorTransform = colorInfo;			
			}
			
			_currentSorting = layer.sorting;
			preloadingImageArray.push(image);
			
			var uiComponent : UIComponent = new UIComponent();
			uiComponent.addChild(image);
			
			decideLayerShowEffect(image, layer);
			
			container.addChild(uiComponent);
			
			return image;
		}
		
		//设置图层动作效果
		private function decideLayerShowEffect(image:Image, layer:Layer):void
		{
			// 图层动作类型（出现）
			if (Util.containsType(Const.ACTION_TYPE_SHOW, layer)) {
				var fade : Fade = new Fade();
				fade.alphaFrom = 0;
				fade.alphaTo = image.alpha;
				fade.duration = Util.getDuration(Const.ACTION_TYPE_SHOW, layer);
				
				fade.target = image;
				fade.play();
			} 
		}
		
		//设置图层动作效果
		private function decideLayerHiddenEffect(image:Image, layer:Layer):void
		{
			//图层动作类型（消失）
			if (Util.containsType(Const.ACTION_TYPE_HIDDEN, layer)) {
				var fade : Fade = new Fade();
				fade.alphaFrom = image.alpha;
				fade.alphaTo = 0;
				fade.duration = Util.getDuration(Const.ACTION_TYPE_HIDDEN, layer);
				
				fade.target = image;
				fade.play();
			}
		}
		
		protected function loadBaseLayer() : void {
			if (baseLayer.baseMapType != Const.BASEMAP_TYPE_IMAGE) {
				return;
			}
			
			baseImage = new Image();
			currentImage = baseImage;
			baseImage.id = baseLayer.layerId;
			baseImage.source = baseLayer.picPath;
			
			//底图指定了大小和位置
			if (baseLayer.fullArea == Const.FULL_SCREEN_NO) {
				baseImage.x = baseLayer.xPos;
				baseImage.y = baseLayer.yPos;
				baseImage.width = baseLayer.width;
				baseImage.height = baseLayer.height;
			} else {
				baseImage.x = 0;
				baseImage.y = 0;
				baseImage.width = container.width;
				baseImage.height = container.height;
			}
			
			//设置底图透明度
			baseImage.alpha = baseLayer.transparency;
			
			//设置底图颜色
			if (baseLayer.color != -1) {
				var colorInfo:ColorTransform = baseImage.transform.colorTransform;
				colorInfo.color = baseLayer.color;
				baseImage.transform.colorTransform = colorInfo;			
			}

			_currentSorting = baseLayer.sorting;
			
			var uiComponent : UIComponent = new UIComponent();
			uiComponent.addChild(baseImage);
			
			//设置图层动作效果
			decideLayerShowEffect(baseImage, baseLayer);
			
			container.addChild(uiComponent);
		}		
		
		/*加载预加载的图层*/
		private function loadPreloadingLayerS():void {
			 var preloadingArray : Array = ExternalInterface.call("loadPreLoadingLayer", currentPageId);
			
			for (var index : Number = 0; index < preloadingArray.length; index ++) {
				currentLayer = new Layer();
				Util.setLayerProperties(currentLayer, preloadingArray[index]);
				preloadingLayerArray.push(currentLayer);
				buildNewImage(currentLayer);
			}
		}
		
		/*初始化首页*/
		public function initAndloadPage(type : String) : void {
			//页面展示
			if (type == Const.OPERAITON_TYPE_SHOW) {
				loadShowBaseLayer();
				
			} else if (type == Const.OPERAITON_TYPE_DESIGN_BASE){ //底图设计
				loadDesignBaseLayer();
			} else if (type == Const.OPERAITON_TYPE_DESIGN_PLAIN) {
				loadDesignPlainLayer();
			}
		}
		
		
		/*刷新页面*/
		public function refresh(obj:Object, arrayString:String, effectId:String) : void {
			if (obj.type == Const.OPERAITON_TYPE_DESIGN_BASE) {
				refreshBaseLayer(obj);
			} else if (obj.type == Const.OPERAITON_TYPE_DESIGN_PLAIN) {
				refreshDesignPlainLayer(obj, arrayString, effectId);
			}
		}
		
		/*刷新普通静态图层*/
		private function refreshDesignPlainLayer(obj:Object, arrayString:String, effectId:String) : void {
			if (arrayString) {
				obj.layerActionlst = JSON.parse(arrayString);
			}
			
			if (!effectId || effectId == "effect1") {
				clearAllLayer();
				
				
				currentLayer = new Layer();
				Util.setLayerProperties(currentLayer, obj);
				
				currentImage = buildNewImage(currentLayer);
			} else {
				if (!currentImage || !currentLayer) return;
				
				Util.setLayerProperties(currentLayer, obj);
				decideLayerHiddenEffect(currentImage, currentLayer);
			}
		}
		
		private function refreshBaseLayer(obj:Object) : void {
			clearAllLayer();
			
			//加载底图图层
			baseLayer = new Layer();
			currentLayer = baseLayer;
			Util.setLayerProperties(baseLayer, obj);
			
			loadBaseLayer();
		}
		
		
		//加载普通静态图层（设计测用）
		private function loadDesignPlainLayer():void
		{
			var layerJsonObj : Object = ExternalInterface.call("loadDesignPlainLayer");
			
			currentLayer = new Layer();
			
			Util.setLayerProperties(currentLayer, layerJsonObj);
			
			currentImage = buildNewImage(currentLayer);
		}
		
		private function loadShowBaseLayer():void
		{
			container.addEventListener(MouseEvent.CLICK, image_clickHandler);
			var baseLayerJsonObj : Object = ExternalInterface.call("getBaseLayer", currentPageId);
			currentPageId = ExternalInterface.call("getCurrentPageId");
			
			//无底图图层时，直接加载预加载图层
			if (baseLayerJsonObj == null) {
				loadPreloadingLayerS();
				return;
			} 
			
			//依次加载底图图层、预加载图层
			baseLayer = new Layer();
			currentLayer = baseLayer;
			Util.setLayerProperties(baseLayer, baseLayerJsonObj);
			
			loadBaseLayer();
			loadPreloadingLayerS();
		}
		
		
		protected function loadDesignBaseLayer() : void {
			var baseLayerJsonObj : Object = ExternalInterface.call("getBaseLayer", currentPageId);
			currentPageId = ExternalInterface.call("getCurrentPageId");		
			
			if (baseLayerJsonObj == null) return;
			
			//加载底图图层
			baseLayer = new Layer();
			currentLayer = baseLayer;
			Util.setLayerProperties(baseLayer, baseLayerJsonObj);
			
			loadBaseLayer();
		}
		
		/*加载下一张图层*/
		private function loadNextLayer() : void {
			var nextLayerJsonObj : Object =  ExternalInterface.call("getNextLayer", currentPageId, currentSorting);
			
			/*如果该页面不存在下一张图层，加载下一个页面*/
			if (nextLayerJsonObj == null) {
				clearAllLayer();
				loadShowBaseLayer();
				return;
			}
			
			currentLayer = new Layer();
			Util.setLayerProperties(currentLayer, nextLayerJsonObj);
			currentImage = buildNewImage(currentLayer);
		}
		
		/*清除当前所有图层*/
		private function clearAllLayer() : void {
				var childNum : Number  = container.numChildren;
				
				while (-- childNum >= 0) {
					container.removeChildAt(childNum);
				}
				
				preloadingImageArray.splice(0);
				
				_currentSorting = 0;
		}
		
		/*清理之前的图层（如果需要的话）*/
		private function clearLayer() : void {
			//清除底图
			if (baseLayer != null && Util.containsType(Const.ACTION_TYPE_HIDDEN, baseLayer)) {
				decideLayerHiddenEffect(baseImage, baseLayer);
			}
			
			//清除预加载图层
			if (preloadingLayerArray != null && preloadingLayerArray.length > 0) {
				for (var index : Number = 0; index < preloadingLayerArray.length; index ++) {
					if (Util.containsType(Const.ACTION_TYPE_HIDDEN, preloadingLayerArray[index])) {
						decideLayerHiddenEffect(preloadingImageArray[index], preloadingLayerArray[index]);
					}
				}
				
				preloadingLayerArray.splice(0);
			}
			
			//清除本图层
			if (currentLayer != null  && 
				currentImage != null && 
				Util.containsType(Const.ACTION_TYPE_HIDDEN, currentLayer)) {
					decideLayerHiddenEffect(currentImage, currentLayer);
			}
		}
		
		/*注册Javascript*/
		protected function registerJsAndLoading() : void {
			if(ExternalInterface.available){
				try {
					//供外部JS调用，即时刷新页面
					ExternalInterface.addCallback("refresh", refresh);
					
					//初始化系统
					initAndloadPage(ExternalInterface.call("getOperaitonType"));
				} catch(error:Error) {
					trace(error)
				}
			} else {
				trace("External interface is not available for this container.");
			}
		}
		
/*********************************************事件定义区（START）****************************************************************************/
		/*页面点击事件，加载下一图层或者下一页面*/
		protected function image_clickHandler(event : MouseEvent):void {
			clearLayer();
			loadNextLayer();
		}
		
		/*应用程序加载完毕，注册Javascript*/
		protected function chart_creationCompleteHandler(event:FlexEvent):void {
			registerJsAndLoading();
			
			if (stage) {
				initStage();
			} else {
				addEventListener(Event.ADDED_TO_STAGE, initStage); 
			}
		}
		
		/*init stage*/
		private function initStage(e:Event = null) : void {
			removeEventListener(Event.ADDED_TO_STAGE, initStage);
			
			stage.addEventListener(Event.RESIZE, resizeDisplay);
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
		}
		
		protected function resizeDisplay(event : Event):void {
			var swfWidth:int = stage.stageWidth;
			var swfHeight:int = stage.stageHeight;
			
			trace("swfWidth =" + swfWidth + "  swfHeight=" + swfHeight);
			
			if (baseLayer == null) return;
			
			if (baseLayer.fullArea == Const.FULL_SCREEN_YES) {
				baseImage.x = 0;
				baseImage.y = 0;
				baseImage.width = container.width;
				baseImage.height = container.height;
			}
		}
		
		
/*********************************************事件定义区（END）****************************************************************************/
/*********************************************get/set方法定义区（START）****************************************************************************/
		
		public function get container():DisplayObjectContainer {
			return _container;
		}
		
		public function set container(value:DisplayObjectContainer):void {
			_container = value;
		}
		
		public function get baseLayer():Layer {
			return _baseLayer;
		}
		
		public function set baseLayer(value:Layer):void {
			_baseLayer = value;
		}
		public function get baseImage():Image
		{
			return _baseImage;
		}
		
		public function set baseImage(value:Image):void
		{
			_baseImage = value;
		}
		
		public function get currentSorting():Number
		{
			return _currentSorting;
		}
		
		public function set currentSorting(value:Number):void
		{
			_currentSorting = value;
		}
		public function get currentImage():Image
		{
			return _currentImage;
		}
		
		public function set currentImage(value:Image):void
		{
			_currentImage = value;
		}
/*********************************************get/set方法定义区（END）****************************************************************************/
	}
}